let R = require('ramda')
let moment = require('moment')
let IO = require('./io.js').IO
let flat = require('./func.js').flat
let ffunc = require('./func.js').n
let f = require('./file.js')
let py = require('./py.js')
let RDIR = require('./config.js').rootDir

let b = (dir) => IO.of(f.res(dir))
                   .map(R.filter(f.isD))
                   .map(R.map(f.res))
                   .map(flat)
                   .map(R.filter(f.isD))
                   .map(R.map(f.res))
                            
exports.filesDeal = (dir, offset) => b(dir)
                            .map(R.map(R.filter( (a) => a.indexOf(moment().subtract(offset, 'months').format("YYYY-MM")) !== -1 )))
                            .map(R.map(R.filter(ffunc(f.isD) )))
                            .map(R.map(R.filter( a => a.indexOf('zip') === -1)))
                            .map(R.map(f.move(offset)))
                            .unsafePerformIO()

exports.dirsInfo = (dir) => b(dir)
                            .map(flat)
                            .map(R.filter(f.isD))
                            .map(R.filter(isLastMonth(2)))
                            // .map(function(f){console.log(f);return f})
                            .map(pythonIn)
                            .unsafePerformIO()

exports.outOfDate = (dir) => b(dir)
                            .map(flat)
                            .map(R.filter(ffunc(f.isD)))
                            .map(R.filter( (a) => a.indexOf('zip') !== -1 ))
                            .map(R.filter(isLastMonth(4)))
                            .unsafePerformIO()

let isLastMonth = R.curry(function(num, path) {
     let n = path.split('/').pop()     
     return R.range(0, 10).reduce(function(t, i) {
            let y = moment().subtract(num + i, 'months').format("YYYY")
            let m = moment().subtract(num + i, 'months').format("MM") 
            return  t || ((n.indexOf(y) !== -1 && n.replace(y,"").indexOf(m) !== -1 ) ? true : false)
        }, false)
})

function pythonIn(arr) {
    if (arr.length === 0 ) return console.log( 'Total cost ' + (Date.now()-START_TIME)/1000/60 + ' minutes.' ) 
    ;(function start (arr) {
            let ele = arr.pop().replace(RDIR,"")
            py.exe(ele)
                .then(function(a) {
                    console.log(a)
                    if (arr.length !== 0 ) start(arr)
                    else console.log( 'Total cost ' + (Date.now()-START_TIME)/1000/60 + ' minutes.' )    
                } )
        }(arr))
}

if (require.main === module) {
    console.log(outOfDate(RDIR))
}